﻿using OpenAiMobile.Services;

namespace OpenAiMobile.ViewModels
{
    internal class LoginPageViewModel : BindableBase
    {
        public Command LoginCommand { get; set; }
        public Command ConvertCommand { get; set; }

        public string Content { get; set; } = "Welcome to .NET MAUI!";

        public string TestText21
        {
            get => _testText21;
            set => SetProperty(ref _testText21, value);
        }

        private string _testText21;

        public string PhoneNumber
        {
            get => _phoneNumber;
            set => SetProperty(ref _phoneNumber, value);
        }

        public string ConvertResult
        {
            get => _convertResult;
            set => SetProperty(ref _convertResult, value);
        }

        public string RegisterStatus
        {
            get => _registerStatus;
            set => SetProperty(ref _registerStatus, value);
        }

        private string _phoneNumber;
        private string _convertResult;
        private string _registerStatus;

        private bool _registerSuccess;

        public LoginPageViewModel(IContainerProvider container)
        {
            var statisticsService = container.Resolve<IStatisticsService>();
            var platformService = container.Resolve<IPlatformService>();

            LoginCommand = new Command(OnLoginAsync);
            ReadDeviceInfo();

            PhoneNumber = platformService.GetPhoneNumberAsync().GetAwaiter().GetResult();

            _registerSuccess = statisticsService.IsRegisterSuccess;
            RegisterStatus = _registerSuccess ? "未注册" : "已注册";
            statisticsService.RegisterSuccess += OnRegisterSuccess;
        }

        public async void OnLoginAsync()
        {
            //if (_registerSuccess)
            {
                await Shell.Current.GoToAsync("//SearchPage");
            }
        }

        private void ReadDeviceInfo()
        {
            var isVirtual = DeviceInfo.Current.DeviceType switch
            {
                DeviceType.Physical => false,
                DeviceType.Virtual => true,
                _ => false
            };

            var sb = new System.Text.StringBuilder();
            sb.AppendLine($"Model: {DeviceInfo.Current.Model}");
            sb.AppendLine($"Manufacturer: {DeviceInfo.Current.Manufacturer}");
            sb.AppendLine($"Name: {DeviceInfo.Current.Name}");
            sb.AppendLine($"OS Version: {DeviceInfo.Current.VersionString}");
            sb.AppendLine($"Idiom: {DeviceInfo.Current.Idiom}");
            sb.AppendLine($"Platform: {DeviceInfo.Current.Platform}");
            sb.AppendLine($"Virtual device? {isVirtual}");
            TestText21 = sb.ToString();
        }

        private void OnRegisterSuccess()
        {
            _registerSuccess = true;
            RegisterStatus = _registerSuccess ? "未注册" : "已注册";
        }
    }
}
